<?php

namespace App\Admin\Controllers;

use App\Admin\Filters\SystemMediaFilter;
use App\Admin\Requests\SystemMediaRequest;
use App\Admin\Resources\SystemMediaResource;
use App\Admin\Models\SystemMedia;
use App\Admin\Models\SystemMediaCategory;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Zip;

class SystemMediaController extends Controller
{
    // 存储下载压缩包的分类名称
    public $zipCate = '压缩包';

    // 存储下载压缩包的目录
    public $uploadsPath = 'uploads/';

    public function destroy(SystemMedia $systemMedia)
    {
        try {
            $systemMedia->delete();
        } catch (FileException $e) {
            return $this->error($e->getMessage());
        }
        return $this->noContent();
    }

    public function edit(SystemMedia $systemMedia)
    {
        return $this->ok(
            SystemMediaResource::make($systemMedia)
        );
    }

    public function update(SystemMediaRequest $request, SystemMedia $systemMedia)
    {
        $inputs = $request->validated();
        $systemMedia->update($inputs);
        return $this->created($systemMedia);
    }

    public function index(SystemMediaFilter $filter)
    {
        $media = SystemMedia::query()
            ->filter($filter)
            ->orderByDesc('id')
            ->paginate();
        
        return $this->ok(
            SystemMediaResource::collection($media)
        );
    }

    public function batchUpdate(SystemMediaRequest $request)
    {
        $inputs = $request->validated();

        SystemMedia::query()
            ->whereIn('id', $request->input('id', []))
            ->update($inputs);

        return $this->created();
    }

    public function batchDestroy(Request $request)
    {
        try {
            SystemMedia::query()
                ->whereIn('id', $request->input('id', []))
                ->get()
                ->each
                ->delete();
        } catch (FileException $e) {
            return $this->error($e->getMessage());
        }
        return $this->noContent();
    }

    public function download(Request $request)
    {
        // 接收文件ID
        $idList = $request->input('id', []);
        // 根据ID查询文件列表
        $systemMediaList = SystemMedia::query()
            ->whereIn('id', $idList)
            ->get();
        // ZIP文件名称
        $zipName = 'download-'.time().'.zip';
        // ZIP文件夹路径
        $zipFolder = SystemMedia::UPLOAD_FOLDER_PREFIX.'/'.str_replace('.zip', '', $zipName).'/';
        if (!file_exists($zipFolder)) {
            mkdir($zipFolder, 0777, true);
        }
        // 复制文件到ZIP文件目录
        foreach ($systemMediaList as $value) {
            $source = ltrim($value['path'], '/');
            $destination = $zipFolder.$value['filename'];
            copy($source, $destination);
        }
        // 拼接ZIP文件路径
        $path = SystemMedia::UPLOAD_FOLDER_PREFIX.'/'.$zipName;
        // 创建ZIP文件
        $zip = Zip::create($path);
        // 添加目录到ZIP
        $zip->add(public_path().'/'.$zipFolder);
        // 关闭ZIP文件
        $zip->close();
        // ZIP文件链接
        $zipUrl = config()->get('app.url').'/'.$path;
        // 删除ZIP文件夹路径
        deldir($zipFolder);
        // 存储到数据库
        DB::beginTransaction();
        // 更新或创建文件分类
        $cateData['name'] = $this->zipCate;
        $cateData['parent_id'] = 0;
        $cate = SystemMediaCategory::updateOrCreate($cateData);
        // 获取文件信息
        $file = UploadedFile::fake()->image($path);
        // 存储文件信息
        $mediaData['origin_filename'] = $zipName;
        $mediaData['filename'] = md5_file($file);
        $mediaData['ext'] = 'zip';
        $mediaData['category_id'] = $cate->id;
        $mediaData['path'] = '/'.$path;
        $mediaData['path_key'] = md5($path);
        $mediaData['size'] = $file->getSize();
        $mediaData['mime_type'] = $file->getMimeType();
        $media = SystemMedia::create($mediaData);
        if ($cate && $media) {
            DB::commit();
        } else {
            DB::rollBack();
        }
        return $this->ok(['zip_url'=>$zipUrl]);
    }
}
